<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      
      <el-form-item label="团队编号" prop="teamCode">
        <el-input
          v-model="queryParams.teamCode"
          placeholder="请输入团队编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队名称" prop="teamName">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入团队名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属车间" prop="workshopId">
        <el-select v-model="queryParams.workshopId" placeholder="请选择所属车间" clearable>
          <el-option
            v-for="item in workshopOptions"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属生产线" prop="lineId">
        <el-select
          v-model="queryParams.lineId"
          placeholder="请选择所属生产线"
          clearable
          filterable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in lineOptions"
            :key="item.lineId"
            :label="item.lineName"
            :value="item.lineId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="团队人数" prop="teamSize">
        <el-input
          v-model="queryParams.teamSize"
          placeholder="请输入团队人数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in sm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['sm:team:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sm:team:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple || hasTeamMembers"
          @click="handleDelete"
          v-hasPermi="['sm:team:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sm:team:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="团队ID" align="center" prop="teamId" />
      <el-table-column label="团队编号" align="center" prop="teamCode" />
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="所属车间" align="center" prop="workshopName"/>
      <el-table-column label="所属生产线" align="center" prop="lineName" />
      <el-table-column label="团队人数" align="center" prop="teamSize" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sm_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['sm:team:edit']"
            v-if="scope.row.teamId !== 0"
          >修改</el-button>
          <el-button 
            link 
            type="primary" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['sm:team:remove']"
            v-if="scope.row.teamId !== 0 && scope.row.teamSize === 0"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产团队对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="teamRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="团队编号" prop="teamCode">
              <el-input v-model="form.teamCode" placeholder="请输入团队编号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="团队名称" prop="teamName">
              <el-input v-model="form.teamName" placeholder="请输入团队名称" />
            </el-form-item>
          </el-col>
         
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
            <el-select 
              v-model="form.workshopId" 
              placeholder="请选择所属车间"
              class="uniform-select"
                @change="handleWorkshopChange"
            >
              <el-option
                v-for="item in workshopOptions"
                :key="item.workshopId"
                :label="item.workshopName"
                :value="item.workshopId"
              />
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属生产线" prop="lineId">
            <el-select 
              v-model="form.lineId" 
              placeholder="请选择所属生产线"
              class="uniform-select"
            >
              <el-option
                v-for="item in lineOptions"
                :key="item.lineId"
                :label="item.lineName"
                :value="item.lineId"
              />
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="团队人数" prop="teamSize">
              <el-input v-model="form.teamSize" placeholder="请输入团队人数" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in sm_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 只在修改时显示成员管理界面 -->
      <template v-if="form.teamId">
      <el-divider content-position="center">团队成员</el-divider>
        <div class="team-members-container">
          <div class="team-member-toolbar" style="margin-bottom: 10px;">
            <el-button type="primary" icon="Plus" @click="handleAddMember">添加成员</el-button>
            <el-button type="warning" icon="Remove" :disabled="!selectedMembers.length" @click="handleRemoveMember">移出成员</el-button>
          </div>
          
          <el-card shadow="hover" class="member-preview-card">
            <template #header>
              <div class="card-header">
                <span>团队成员预览</span>
                <span class="member-count">共 {{ memberList.length }} 人</span>
              </div>
            </template>
            <el-empty description="暂无团队成员，请点击添加成员按钮" v-if="memberList.length === 0"></el-empty>
            <div class="member-preview-list" v-else>
              <el-row :gutter="16">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="(member, index) in memberList" :key="index" class="member-preview-item">
                  <el-card shadow="hover" :body-style="{ padding: '12px' }">
                    <div class="member-card-content">
                      <div class="member-avatar">
                        <el-avatar :size="40" icon="User"></el-avatar>
                      </div>
                      <div class="member-info">
                        <div class="member-name">{{ member.memberName || '成员' }}</div>
                        <div class="member-position">{{ member.position || '未设置职位' }}</div>
                        <el-tag type="success" size="small" v-if="member.isLeader === '0'" style="margin-top: 5px;">组长</el-tag>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </el-card>
          
          <el-table :data="memberList" border style="margin-top: 15px" @selection-change="handleMemberSelectionChange" v-if="memberList.length > 0">
            <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="成员ID" align="center" prop="memberId" />
    <!-- <el-table-column label="用户名称" align="center" prop="userName" /> -->
    <el-table-column label="成员名称" align="center" prop="memberName" />
    <el-table-column label="职位" align="center" prop="position" />
    <el-table-column label="加入日期" align="center" prop="joinDate" width="180">
      <template #default="scope">
        <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
      </template>
    </el-table-column>
    <el-table-column label="是否组长" align="center" prop="isLeader">
      <template #default="scope">
        <dict-tag :options="sm_is_leader" :value="scope.row.isLeader"/>
      </template>
    </el-table-column>
    <el-table-column label="状态" align="center" prop="status">
      <template #default="scope">
        <dict-tag :options="sm_member_status" :value="scope.row.status"/>
      </template>
    </el-table-column>
            <el-table-column label="操作" align="center" width="150">
              <template #default="scope">
                <el-button 
                  link 
                  type="primary" 
                  @click="toggleLeaderStatus(scope.row)"
                >
                  {{ scope.row.isLeader === '0' ? '取消组长' : '设为组长' }}
                </el-button>
              </template>
            </el-table-column>
  </el-table>
        </div>
      </template>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 成员选择对话框 -->
    <el-dialog 
      :title="'选择成员'" 
      v-model="memberSelectOpen" 
      width="800px" 
      append-to-body
      @opened="handleMemberDialogOpen"
      @closed="handleMemberDialogClose"
    >
      <el-form :model="memberQueryParams" ref="memberQueryRef" :inline="true" label-width="68px">
        <!-- <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="memberQueryParams.userName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleMemberQuery"
          />
        </el-form-item> -->
         <el-form-item label="成员名称" prop="memberName">
          <el-input
            v-model="memberQueryParams.memberName"
            placeholder="请输入成员名称"
            clearable
            @keyup.enter="handleMemberQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleMemberQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetMemberQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="memberLoading" :data="availableMemberList" border stripe highlight-current-row>
        <el-table-column label="成员ID" align="center" prop="memberId" />
        <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
        <el-table-column label="成员名称" align="center" prop="memberName" />
        <!-- <el-table-column label="用户名称" align="center" prop="userName" /> -->
        <el-table-column label="所属团队" align="center" prop="teamName">
          <template #default="scope">
            <span v-if="scope.row.teamName">{{ scope.row.teamName }}</span>
            <el-tag type="info" v-else>暂无团队</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="职位" align="center" prop="position">
          <template #default="scope">
            <span v-if="scope.row.position">{{ scope.row.position }}</span>
            <el-tag type="info" v-else>暂未设置</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否组长" align="center" prop="isLeader" width="100">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isLeader === '0'">是</el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === '0'">正常</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === '1'">离开</el-tag>
            <el-tag type="info" v-else>{{ scope.row.status || '正常' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              icon="Plus" 
              @click="confirmAddMember(scope.row)"
              :disabled="isAlreadySelected(scope.row)">
              {{ isAlreadySelected(scope.row) ? '已选择' : '选择' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="memberTotal > 0"
        :total="memberTotal"
        v-model:page="memberQueryParams.pageNum"
        v-model:limit="memberQueryParams.pageSize"
        @pagination="getAvailableMemberList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="memberSelectOpen = false">取 消</el-button>
          <el-button type="primary" @click="confirmSelectedMembers">确认选择</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Team">

import { listTeam, getTeam, delTeam, addTeam, updateTeam, listWorkshop, listLine } from "@/api/sm/team";
import { generateTeamCode } from "@/utils/generator";
import { listMember, getMember, delMember, addMember, updateMember, batchAddMember, listTeam as teamListTeam } from "@/api/sm/member";
import { listPost } from "@/api/system/post";
const memberList = ref([]);
const tempMemberList = ref([]); // 临时存储选择的成员，确认时才保存
const lineOptions = ref([]);
const workshopOptions = ref([]);
const { proxy } = getCurrentInstance();
const { sm_status } = proxy.useDict('sm_status');
const { sm_member_status, sm_is_leader } = proxy.useDict('sm_member_status', 'sm_is_leader');
const teamList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedMembers = ref([]);
const memberSelectOpen = ref(false);
const availableMemberList = ref([]);
const memberLoading = ref(false);
const memberTotal = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teamCode: null,
    teamName: null,
    workshopId: null,
    lineId: null,
    teamSize: null,
    status: null,
  },
  rules: {
    teamCode: [
      { required: true, message: "团队编号不能为空", trigger: "blur" }
    ],
    teamName: [
      { required: true, message: "团队名称不能为空", trigger: "blur" }
    ],
  },
  memberQueryParams: {
    pageNum: 1,
    pageSize: 10,
    // userName: null,
    memberName: null,
    excludeTeamId: null,
    memberId: null,
  },
});

const { queryParams, form, rules, memberQueryParams } = toRefs(data);

/** 查询生产团队列表 */
function getList() {
  loading.value = true;
  listTeam(queryParams.value).then(response => {
    teamList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
  // 清空临时成员列表
  tempMemberList.value = [];
}

// 表单重置
function reset() {
  form.value = {
    teamId: null,
    teamCode: null,
    teamName: null,
    workshopId: null,
    lineId: null,
    teamSize: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("teamRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.teamId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 自动生成团队编号
  form.value.teamCode = generateTeamCode();
  // 清空成员列表
  memberList.value = [];
  tempMemberList.value = [];
  // 设置初始团队人数为0
  form.value.teamSize = 0;
  // 设置默认状态为正常
  form.value.status = "0";
  open.value = true;
  title.value = "添加生产团队";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _teamId = row.teamId || ids.value;
  getTeam(_teamId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改生产团队";
    
    // 获取团队成员数据
    getMemberList();
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["teamRef"].validate(valid => {
    if (valid) {
      // 检查团队成员中是否有多个组长
      const leaders = memberList.value.filter(member => member.isLeader === '0');
      if (leaders.length > 1) {
        proxy.$modal.msgError("一个小组只能有一个组长，请检查后重试");
        return;
      }
      
      if (form.value.teamId != null) {
        // 修改团队
        updateTeam(form.value).then(response => {
          // 保存团队成员
          if (tempMemberList.value.length > 0) {
            saveMemberChanges().then(() => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            }).catch(error => {
              console.error("保存成员失败:", error);
              proxy.$modal.msgError("保存成员失败: " + (error.message || "未知错误"));
            });
          } else {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          }
        }).catch(error => {
          console.error("更新团队失败:", error);
          proxy.$modal.msgError("更新团队失败: " + (error.message || "未知错误"));
        });
      } else {
        // 新增团队
        addTeam(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("新增团队失败:", error);
          proxy.$modal.msgError("新增团队失败: " + (error.message || "未知错误"));
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _teamIds = row.teamId || ids.value;
  proxy.$modal.confirm('是否确认删除生产团队编号为"' + _teamIds + '"的数据项？').then(function() {
    return delTeam(_teamIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sm/team/export', {
    ...queryParams.value
  }, `team_${new Date().getTime()}.xlsx`)
}

// 在组件挂载时获取车间选项
onMounted(() => {
  // 获取车间列表
  listWorkshop().then(response => {
    workshopOptions.value = response.rows || response.data;
  });
  listLine().then(response => {
    lineOptions.value = response.rows || response.data;
  });
  
  getList();
});

/** 处理成员选择变更 */
function handleMemberSelectionChange(selection) {
  selectedMembers.value = selection.map(item => item.memberId);
}

/** 添加成员按钮操作 */
function handleAddMember() {
  // 设置查询参数，排除当前团队的成员
  memberQueryParams.value.excludeTeamId = form.value.teamId;
  
  // 重置查询，清空其他条件
  resetMemberQuery();
  
  // 打开选择对话框
  memberSelectOpen.value = true;
}

/** 获取可选成员列表 */
function getAvailableMemberList() {
  memberLoading.value = true;
  
  // 清理查询条件，明确查询未分配的成员
  const params = {
    pageNum: memberQueryParams.value.pageNum,
    pageSize: memberQueryParams.value.pageSize,
    // userName: memberQueryParams.value.userName,
    memberName: memberQueryParams.value.memberName,
    teamId: 0  // 明确指定查询teamId为0的成员
  };
  
  // 查询所有未分配团队的成员
  listMember(params).then(response => {
    // 获取所有成员并修正可能错误的isLeader值
    const members = response.rows || [];
    console.log("原始成员数据:", members);
    
    // 确保未分配团队的成员isLeader值为"1"(表示不是组长)
    availableMemberList.value = members.map(member => {
      const correctedMember = {
        ...member,
        isLeader: member.teamId === 0 ? "1" : member.isLeader // 未分配团队的成员不可能是组长
      };
      console.log(`成员ID: ${member.memberId}, 原始isLeader: ${member.isLeader}, 修正后: ${correctedMember.isLeader}`);
      return correctedMember;
    });
    
    console.log("修正后的成员数据:", availableMemberList.value);
    
    // 更新总数
    memberTotal.value = availableMemberList.value.length;
    memberLoading.value = false;
  }).catch(error => {
    console.error("获取可用成员列表失败:", error);
    memberLoading.value = false;
  });
}

/** 成员重置按钮操作 */
function resetMemberQuery() {
  // 保留分页参数，重置其他条件
  memberQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    // userName: null,
    memberName: null
  };
  
  // 重新加载数据
  getAvailableMemberList();
}

/** 成员搜索按钮操作 */
function handleMemberQuery() {
  memberQueryParams.value.pageNum = 1;
  getAvailableMemberList();
}

/** 确认添加成员 */
function confirmAddMember(row) {
  // 检查是否已经在临时列表中
  if (tempMemberList.value.some(item => item.memberId === row.memberId)) {
    proxy.$modal.msgError("该成员已在列表中");
    return;
  }

  // 确保组长状态正确
  let leaderStatus = "1"; // 默认为非组长(1表示否)
  // 如果row.isLeader不正确，强制设置为"1"(表示非组长)
  if (row.teamId === 0 || !row.teamId) {
    leaderStatus = "1"; // 未分配团队的成员一定不是组长
  } else {
    leaderStatus = row.isLeader === "0" ? "0" : "1"; // 0是组长，1不是组长
  }

  // 确定操作类型
  let action = 'add';
  if (row.memberId) {
    // 如果已有memberId，则是更新现有成员而不是添加新成员
    action = 'update';
  }

  // 创建新的成员对象
  const newMember = {
    ...row,
    teamId: form.value.teamId,
    isLeader: leaderStatus,
    status: row.status || "0", // 默认状态为正常
    joinDate: row.joinDate || new Date().toISOString().slice(0, 10), // 如果没有加入日期，默认为当前日期
    _action: action // 使用上面确定的操作类型
  };
  
  console.log("添加的成员数据:", newMember);
  
  // 添加到临时列表
  tempMemberList.value.push(newMember);
  
  // 更新显示
  updateMemberDisplay();
  
  // 从可用列表中移除该成员
  const index = availableMemberList.value.findIndex(m => m.memberId === row.memberId);
  if (index !== -1) {
    availableMemberList.value.splice(index, 1);
  }
  
  // 显示成功消息


  proxy.$modal.msgSuccess(`已添加成员"${row.userName || '用户'}"`);

  // proxy.$modal.msgSuccess(`已添加成员"${row.userName || '用户'}"`);
  proxy.$modal.msgSuccess(`已添加成员"${row.memberName || '成员'}"`);

}
/** 获取团队成员列表 */
function getMemberList() {
  if (!form.value.teamId) {
    memberList.value = [];
    form.value.teamSize = 0;
    return;
  }
  
  listMember({ teamId: form.value.teamId }).then(res => {
    const members = res.rows || res.data;
    console.log("获取到的团队成员原始数据:", members);
    
    // 确保成员的isLeader值正确，规范为0表示是组长，1表示不是组长
    memberList.value = members.map(member => {
      return {
        ...member,
        isLeader: member.isLeader === "0" ? "0" : "1" // 确保组长状态是0或1
      };
    });
    
    console.log("规范化后的团队成员数据:", memberList.value);
    
    // 更新团队人数
    form.value.teamSize = memberList.value.length;
    
    // 初始化临时成员列表，标记现有成员为update状态
    tempMemberList.value = JSON.parse(JSON.stringify(memberList.value)).map(member => ({
      ...member,
      _action: 'update'  // 标记为已存在的成员
    }));

    console.log("临时成员列表初始化:", tempMemberList.value);
    
    // 更新显示
    updateMemberDisplay();
  });
}

/** 更新显示的成员列表 */
function updateMemberDisplay() {
  // 过滤掉标记为删除的成员
  const activeMembers = tempMemberList.value.filter(member => member._action !== 'remove');
  // 更新显示列表
  memberList.value = activeMembers;
  // 更新团队人数
  form.value.teamSize = activeMembers.length;
}

/** 验证团队组长 */
function validateLeader() {
  // 检查当前团队成员中是否已有组长
  const leaders = memberList.value.filter(member => member.isLeader === '0');
  return leaders.length <= 1;
}

/** 修改saveMemberChanges函数，在保存成员前验证组长 */
function saveMemberChanges() {
  // 保存前验证组长
  if (!validateLeader()) {
    return Promise.reject(new Error("一个小组只能有一个组长，请检查后重试"));
  }
  
  console.log("保存前的成员数据:", tempMemberList.value);
  
  // 根据操作类型批量处理
  const addMembers = tempMemberList.value.filter(m => m._action === 'add' && !m.memberId);
  const updateMembers = tempMemberList.value.filter(m => 
    (m._action === 'update' || m._action === 'update_team' || m.memberId) && m._action !== 'remove'
  );
  const removeMembers = tempMemberList.value.filter(m => m._action === 'remove');
  
  console.log("新增成员:", addMembers);
  console.log("更新成员:", updateMembers);
  console.log("移除成员:", removeMembers);
  
  const promises = [];
  
  // 单个添加新成员，避免使用批量添加的API
  addMembers.forEach(member => {
    if (!member.memberId) { // 只有真正的新成员才创建
      const addData = {
        userId: member.userId,
        teamId: form.value.teamId,
        position: member.position,
        joinDate: member.joinDate,
        isLeader: member.isLeader || "1", // 确保有组长状态，默认为非组长
        status: member.status || "0"
      };
      
      promises.push(addMember(addData));
    }
  });
  
  // 批量更新成员
  updateMembers.forEach(member => {
    // 确保成员有memberId
    if (member.memberId) {
      // 如果是原本在其他团队的成员，修改其团队ID
      if (member.teamId !== form.value.teamId) {
        member.teamId = form.value.teamId;
      }
      
      const updateData = {
        memberId: member.memberId,
        // userId: member.userId,
        memberName: member.memberName,
        teamId: member.teamId,
        position: member.position,
        joinDate: member.joinDate,
        isLeader: member.isLeader || "1", // 确保有组长状态，默认为非组长
        status: member.status || "0"
      };
      
      promises.push(updateMember(updateData));
    }
  });
  
  // 批量移出成员
  if (removeMembers.length > 0) {
    // 将成员从团队中移出，设置teamId为0（未分配）
    removeMembers.forEach(member => {
      // 如果有成员ID，修改其所属团队为0
      if (member.memberId) {
        const updateData = {
          memberId: member.memberId,
          teamId: 0, // 设置为未分配团队
          isLeader: "1" // 确保不是组长
        };
        promises.push(updateMember(updateData));
      }
    });
  }
  
  return Promise.all(promises);
}

/** 检查成员是否已经被选择 */
function isAlreadySelected(member) {
  return tempMemberList.value.some(m => 
    m._action !== 'remove' && m.memberId === member.memberId
  );
}

/** 确认选择的成员 */
function confirmSelectedMembers() {
  // 只更新显示列表，不清除原有成员
  updateMemberDisplay();
  // 关闭选择对话框
  memberSelectOpen.value = false;
  // 显示成功消息
  proxy.$modal.msgSuccess("成员已添加到团队列表");
}

/** 从临时列表中移除成员 */
function removeFromTemp(member) {
  const index = tempMemberList.value.findIndex(m => 
    (m.memberId && m.memberId === member.memberId) || 
    // (!m.memberId && m.userId === member.userId)
    (!m.memberId && m.memberName === member.memberName)
  );
  
  if (index !== -1) {
    // 如果是已有成员，标记为从团队移出；如果是新添加的成员，直接移除
    if (member.memberId && member._action === 'update') {
      tempMemberList.value[index]._action = 'remove';
      tempMemberList.value[index].isLeader = "1"; // 设置为非组长(1表示否)
    } else {
      tempMemberList.value.splice(index, 1);
    }
    updateMemberDisplay();
  }
}

/** 处理车间选择变更 */
function handleWorkshopChange(workshopId) {
  // 清空当前选中的生产线
  form.value.lineId = null;
  
  // 如果没有选择车间，则清空生产线选项
  if (!workshopId) {
    lineOptions.value = [];
    return;
  }
  
  // 加载该车间下的生产线
  getLinesByWorkshop(workshopId);
}

/** 根据车间ID获取生产线列表 */
function getLinesByWorkshop(workshopId) {
  // 传入车间ID参数，获取该车间下的生产线
  listLine({ workshopId }).then(response => {
    lineOptions.value = response.rows || response.data;
  });
}

/** 修改availableMembers的获取方式 */
function updateAvailableMembers() {
  // 获取所有成员
  listMember().then(response => {
    const allMembers = response.rows || [];
    // 过滤掉已经在团队中的成员
    const currentTeamMembers = tempMemberList.value.map(m => m.memberId);
    availableMemberList.value = allMembers.filter(member => 
      !currentTeamMembers.includes(member.memberId)
    );
  });
}

/** 移出成员 */
function handleRemoveMember() {
  if (!selectedMembers.value.length) {
    proxy.$modal.msgError("请选择要移出的成员");
    return;
  }
  
  proxy.$modal.confirm('确认将所选成员移出当前团队吗？').then(() => {
    // 遍历选中的成员ID
    selectedMembers.value.forEach(memberId => {
      // 在当前显示的成员列表中查找
      const member = memberList.value.find(m => m.memberId === memberId);
      if (member) {
        // 在临时列表中查找成员索引
        const index = tempMemberList.value.findIndex(m => m.memberId === memberId);
        
        // 如果成员在临时列表中
        if (index !== -1) {
          // 检查成员的状态
          if (tempMemberList.value[index]._action === 'add') {
            // 如果是新添加的成员，直接从列表中移除
            tempMemberList.value.splice(index, 1);
          } else {
            // 如果是已有成员，标记为从团队移出
            tempMemberList.value[index]._action = 'remove';
            // 确保取消组长身份
            tempMemberList.value[index].isLeader = "1";
          }
        }
      }
    });
    
    // 更新显示的成员列表
    updateMemberDisplay();
    // 清空选中的成员
    selectedMembers.value = [];
    proxy.$modal.msgSuccess("成员已标记为移出团队，保存团队时生效");
  }).catch(() => {});
}

const hasTeamMembers = computed(() => {
  return teamList.value.some(team => team.teamSize > 0);
});

// 添加下面的函数，在关闭成员选择对话框时的处理
function handleMemberDialogClose() {
  // 不要调用 updateMemberDisplay，保留原有成员列表
  // 特意不做任何操作，防止清除已有成员数据
}

/** 切换组长状态 */
function toggleLeaderStatus(row) {
  // 检查是否已经是组长
  const isCurrentlyLeader = row.isLeader === '0';
  
  // 如果当前是组长，直接取消组长身份
  if (isCurrentlyLeader) {
    row.isLeader = '1';
    
    // 在tempMemberList中找到对应记录并更新
    const index = tempMemberList.value.findIndex(m => m.memberId === row.memberId);
    if (index !== -1) {
      tempMemberList.value[index].isLeader = '1';
      
      // 如果原来没有标记为update，添加标记
      if (!tempMemberList.value[index]._action) {
        tempMemberList.value[index]._action = 'update';
      }
    }
    
    proxy.$modal.msgSuccess("已取消组长身份");
    return;
  }
  
  // 如果当前不是组长，检查团队是否已有组长
  const hasLeader = memberList.value.some(member => 
    member.isLeader === '0' && member.memberId !== row.memberId
  );
  if (hasLeader) {
    proxy.$modal.msgError("团队已有组长，一个小组只能有一个组长");
    return;
  }
  
  // 设置为组长
  row.isLeader = '0';
  
  // 在tempMemberList中找到对应记录并更新
  const index = tempMemberList.value.findIndex(m => m.memberId === row.memberId);
  if (index !== -1) {
    tempMemberList.value[index].isLeader = '0';
    
    // 如果原来没有标记为update，添加标记
    if (!tempMemberList.value[index]._action) {
      tempMemberList.value[index]._action = 'update';
    }
  }
  
  proxy.$modal.msgSuccess("已设置为组长");
}

// 添加下面的函数，在打开成员选择对话框时的处理
function handleMemberDialogOpen() {
  // 打开对话框时获取可用成员列表
  getAvailableMemberList();
}

</script>

<style scoped>
.member-preview {
  margin-top: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background-color: #f8f9fa;
}

.team-member-toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 10px;
}

.uniform-select {
  width: 100%;
}

.team-members-container {
  margin-top: 15px;
}

.member-preview-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.member-count {
  font-size: 0.875em;
  color: #909399;
}

.member-preview-list {
  margin-top: 10px;
}

.member-preview-item {
  margin-bottom: 10px;
}

.member-card-content {
  display: flex;
  align-items: center;
}

.member-avatar {
  margin-right: 10px;
}

.member-info {
  display: flex;
  flex-direction: column;
}

.member-name {
  font-size: 1em;
  font-weight: 600;
}

.member-position {
  font-size: 0.875em;
  color: #909399;
}
</style>
